package PDFd.Instance;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.thoughtworks.xstream.XStream;

/**
* <p>Title: InstanceManager</p>
* <p>Description: Instance manager is
* responsible for saving and loading all
* pdf files you have in the past </p>
* @author Matt, Tom, Andrew, Kong
* @email matt.mckay@my.uwrf.edu,tom.florin@my.uwrf.edu,
* andre w.kathan@my.uwrf.edu,kong.xiong-1@my.uwrf.edu
* @date December 1st,2011
* */

public class InstanceManager {
	private static final String XML_PDFD_INSTANCES = "HERE_IS_AN_XML_FILE_DR_VARG.xml";
	private static InstanceManager im;
	private Context c;
	public List<PDFdInstance> instances;
	private InstanceManager(Context c) throws IOException {
		this.c = c;
		loadInstances();
	}
/**
 * Loads an instance of pdf
 * @throws IOException
 */
	@SuppressWarnings("unchecked")
	private void loadInstances() throws IOException {
		String[] fileList = c.fileList();
		boolean settingsFileFound = false;
		for (String file : fileList) {
			if (file.equals(XML_PDFD_INSTANCES)) {
				settingsFileFound = true;
				break;
			}
		}
		if (!settingsFileFound)
			this.instances = new ArrayList<PDFdInstance>();
		else {
			FileInputStream f = c.openFileInput(XML_PDFD_INSTANCES);
			XStream xstream = new XStream();
			xstream.registerConverter(new BitmapConverter());
			this.instances = ((List<PDFdInstance>) (xstream.fromXML(f)));
			f.close();
		}
	}
	
	/**
	 * Returns the an instance of a pdf
	 * @return im
	 * @throws PersistanceException
	 */
	public static InstanceManager getInstanceManager() throws PersistanceException {
		if(im == null) {
			throw new PersistanceException("No context provided! Please get an instance manager with a Context before attempting to get it without a context later.");
		}
		return im;
	}
	
	/**
	 * Returns saved instances.
	 * @param fileContext
	 * @return
	 * @throws PersistanceException
	 */
	public static InstanceManager getInstanceManager(Context fileContext) throws PersistanceException {
		if(im == null) {
			try {
				im = new InstanceManager(fileContext);
			} catch (IOException e) {
				throw new PersistanceException("Unable to load saved instances",e);
			}
		}
		return im;
	}
	
	/**
	 * 
	 */
	public void persist() {

		final Handler toastMessage = new Handler() {
	        public void handleMessage(Message msg) {
				Toast.makeText(c, (String) msg.obj, Toast.LENGTH_SHORT).show();
	        }
	    };
		Runnable r = new Runnable() {
/**
 * This method sends outs messages 
 * @param message
 */
			private void sendMessage(String message) {
	            Message msg = toastMessage.obtainMessage();
	            msg.obj = message;
	            toastMessage.sendMessage(msg);
			}
			
			/**
			 * This method creates a saved instance
			 */
			public void run() {
				try {
					XStream xstream = new XStream();
					xstream.registerConverter(new BitmapConverter());
					FileOutputStream fos = c.openFileOutput(XML_PDFD_INSTANCES, Context.MODE_PRIVATE);
					xstream.toXML(instances, fos);
					sendMessage("Files saved!");
				} catch (FileNotFoundException e) {
					sendMessage("Unable to save file!");
					e.printStackTrace();
				}
			}
		};
		Thread rt = new Thread(r);
		rt.start();
	}
	
}
